from math import sin, cos, pi, sqrt
from Particle import Particle
import sys
import pyglet
import Tkinter as tk

TWO_PI = 2 * pi 

class Display(object):
    def __init__(self, window_width, window_height, radius, update_time, vertices_number):
        self.window_width = window_width
        self.window_height = window_height
        self.radius = radius
        self.update_time = update_time
        self.vertices_number = vertices_number

    def draw_circle(self, dt):
        self.particle.move(dt)
        self.particle.bounce((0, self.window_width, 0, self.window_height))

class TkinterDisplay(Display):
    def __init__(self, window_width, window_height, radius, update_time, vertices_number):
        super(TkinterDisplay, self).__init__(window_width, window_height, radius, update_time, vertices_number)
        self.canvas = tk.Canvas(tk.Tk(), width=self.window_width, height=self.window_height, bg='black')
        self.canvas.pack()

    def draw_circle(self, dt):
        super(TkinterDisplay, self).draw_circle(dt)
        self.canvas.delete(tk.ALL)
        self.canvas.create_oval(self.particle.x - self.radius, self.particle.y - self.radius, self.particle.x + self.radius, self.particle.y + self.radius, outline='yellow')
        self.canvas.after(17, self.draw_circle, self.update_time)

    def go(self):
        self.draw_circle(0)
        tk.mainloop()


class PygletDisplay(Display):
    def __init__(self, window_width, window_height, radius, update_time, vertices_number):
        super(PygletDisplay, self).__init__(window_width, window_height, radius, update_time, vertices_number)
        self.window = pyglet.window.Window(self.window_width, self.window_height)
        self.fps_display = pyglet.clock.ClockDisplay()

        @self.window.event
        def on_draw():
            self.window.clear()

            def circle_vertices():
                delta_angle = TWO_PI / self.vertices_number
                angle = 0
                while angle < TWO_PI:
                    yield self.particle.x + self.radius * cos(angle)
                    yield self.particle.y + self.radius * sin(angle)
                    angle += delta_angle

            pyglet.gl.glColor3f(1.0, 1.0, 0)
            pyglet.graphics.draw(self.vertices_number, pyglet.gl.GL_LINE_LOOP,
                                 ('v2f', tuple(circle_vertices())))

            self.fps_display.draw()

    def go(self):
        pyglet.clock.schedule_interval(self.draw_circle, self.update_time)
        pyglet.app.run()

window_width, window_height = 600, 400
update_time = 1 / 60.0
radius = 30
vertices_number = 20
particle = Particle(radius, (window_width / 2, window_height / 2), (80.0, 150.0))

if sys.argv[1] == "tk":
    particle.draw(TkinterDisplay(window_width, window_height, radius, update_time, vertices_number))
else:
    particle.draw(PygletDisplay(window_width, window_height, radius, update_time, vertices_number))
